package com.ynding.springboot.common.utils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p> TODO  Dto，Vo，entity 转换工具类</p>
 *
 * @author ynding
 * @version 2021/5/12
 **/
public class BeanDtoVoUtils {

    /**
     * 实体类转换
     *
     * @return
     */
    public static <D, T> D toDtoBean(T source, Class<D> dClass) {
        if (source != null) {
            D d = null;
            try {
                d = dClass.newInstance();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            BeanUtils.copyProperties(source, d);
            return d;
        }
        return null;
    }

    /**
     * 列表转换
     *
     * @return
     */
    public static <D, T> List<D> toDtoList(List<T> source, Class<D> dClass) {
        if (CollectionUtil.isNotEmpty(source)) {
            List<D> ds = source.stream().map(m -> {
                D d = null;
                try {
                    d = dClass.newInstance();
                } catch (InstantiationException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
                BeanUtils.copyProperties(m, d);
                return d;
            }).collect(Collectors.toList());
            return ds;
        }
        return null;
    }

    /**
     * 分页转换,简化版
     *
     * @return
     */
    public static <D, T> Page<D> toDtoPage(Page<T> source, Class<D> dClass) {
        if (source != null) {
            Page<D> dest = null;
            if (CollUtil.isNotEmpty(source.getContent())) {
                List<T> list = source.getContent();
                List<D> ds = list.stream().map(m -> {
                    D d = null;
                    try {
                        d = dClass.newInstance();
                    } catch (InstantiationException e) {
                        e.printStackTrace();
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                    BeanUtil.copyProperties(m, d);
                    return d;
                }).collect(Collectors.toList());
                dest = new PageImpl<D>(ds, PageRequest.of(source.getNumber(), source.getSize())
                        , source.getTotalElements());
            }
            return dest;
        }
        return null;
    }


}
